package org.pok.sort;

import java.util.LinkedList;
import java.util.List;

public class Partition {

  protected List<Item> source;

  // OK
  public Partition(List<Item> source) {
    this.source = new LinkedList<Item>(source);
  }
  
  // OK
  public Partition() {
    this.source = new LinkedList<Item>();
  }

  // OK
  public void addItem(Item item) {
    source.add(item);
  }

  public List<Item> sort() {
    if (isTrivial()){
      return source;
    } 
    Pivot pivot = PivotStrategy.choosePivot(source);
    split(pivot);
    return pivot.sortAndJoinSubpartitions();
  }

  private boolean isTrivial() {
    return source.size() <= 1;
  }
  
  private class Splitter {
	  private boolean skipFirst = true;

	  private Pivot pivot;

	public Splitter(Pivot pivot) {
		this.pivot = pivot;
	}
	  
	  
  }

  private void split(Pivot pivot) {
	  
	Splitter splitter = new Splitter(pivot);
	
    boolean skipFirst = true;
    for (Item current : source) {
      if (skipFirst && pivot.equals(current)) {
        skipFirst = false;
      } else {
    	pivot.storeIntoSubpartition(current);
      }
    }
  }

}
